var chalk = require('chalk')
let ENV_NAME = process.env.name
var name = process.argv[2]
console.log(process.argv)
var shell = require('shelljs')
const childProcess = require('child_process')
var exec = shell.exec
const branch = childProcess
  .execSync('git rev-parse --abbrev-ref HEAD')
  .toString()
  .replace(/\s+/, '')
if (!name) {
  console.log(chalk.red(`请填写commit信息 eg: npm run ${ENV_NAME || 'push'} -- 'git 提交'`))
  process.exit(0)
}
process.env.COMMITNAME = name

function compile() {
  if (ENV_NAME === 'build' || ENV_NAME === 'dist' || ENV_NAME === 'beta') {
    if (ENV_NAME === 'build') {
      require('../build/build')
    }
    if (ENV_NAME === 'beta') {
      require('../build/beta')
      console.log('-----------------')
    }
    if (ENV_NAME === 'beta') {
      commit()
    }
  }
}
function commit() {
  console.log('git add')
  if (exec('git add .').code !== 0) {
    process.stdout.write('Error: Git add failed \n')
    process.exit(1)
  }
  console.log('git commit')
  let res = exec(`git commit -m "${name}"`)
  // console.log(chalk.green(res.stdout))
  if (res.stdout.indexOf('fatal') !== -1) return console.log(chalk.red(`git 提交失败!`))
}
function push() {
  console.log('git push')
  if (exec(`git push origin ${branch}`).code !== 0) {
    process.stdout.write('Error: Git push failed \n')
    process.exit(1)
  } else {
    console.log('git 提交成功')
  }
}
let pullResult
function pull() {
  try {
    console.log('git pull')
    pullResult = exec(`git pull origin ${branch}`)
    // console.log(pullResult)
  } catch (e) {
    process.exit(1)
  }
  if (pullResult.code !== 0) {
    if (pullResult.stdout.indexOf('conflict') !== -1) {
      console.log(chalk.red(`代码冲突`))
      return process.exit(0)
    } else {
      if (pullResult.stdout) {
        commit()
        pull()
      }
    }
  }
  if (pullResult.stdout.indexOf('Already up-to-date') === -1) {
    process.stdout.write('git代码有更新，已经拉取啦 \n')
  } else {
    process.stdout.write('git代码暂无更新 \n')
  }
}
commit()
pull()
compile()
push()
